package com.ruoyi.project.custom.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataScope;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.common.utils.SnowflakeIdWorker;
import com.ruoyi.project.custom.domain.CustomContact;
import com.ruoyi.project.custom.domain.CustomInfo;
import com.ruoyi.project.custom.domain.CustomOperator;
import com.ruoyi.project.custom.domain.vo.CustomAgreementVo;
import com.ruoyi.project.custom.domain.vo.HandoverParamVo;
import com.ruoyi.project.custom.mapper.CustomContactMapper;
import com.ruoyi.project.custom.mapper.CustomInfoMapper;
import com.ruoyi.project.custom.mapper.CustomOperatorMapper;
import com.ruoyi.project.custom.service.ICustomGroupService;
import com.ruoyi.project.custom.service.ICustomInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-06-26
 */
@Service
public class CustomInfoServiceImpl implements ICustomInfoService 
{
    @Autowired
    private CustomInfoMapper customInfoMapper;
    @Autowired
    private CustomContactMapper contactMapper;
    @Autowired
    private CustomOperatorMapper operatorMapper;
    @Autowired
    private ICustomGroupService groupService;

    /**
     * 查询【客户信息】
     * 
     * @param id
     * @return
     */
    @Override
    public CustomInfo selectCustomInfoById(String id)
    {
        CustomInfo customInfo = customInfoMapper.selectCustomInfoById(id);
        return customInfo;
    }

    /**
     * 查询【客户信息】列表
     * 
     * @param customInfo
     * @return
     */
    @Override
    @DataScope(deptAlias = "t2", userAlias = "t2")
    public List<CustomInfo> selectCustomInfoList(CustomInfo customInfo)
    {
        return customInfoMapper.selectCustomInfoList(customInfo);
    }

    @Override
    public List<CustomInfo> selectNotAllocatedCustomList(CustomInfo customInfo) {
        return customInfoMapper.selectNotAllocatedCustomList(customInfo);
    }

    @Override
    @DataScope(deptAlias = "t2", userAlias = "t2")
    public List<CustomInfo> selectMySignedCustomList(CustomInfo customInfo) {
        return customInfoMapper.selectMySignedCustomList(customInfo);
    }

    @Override
    public List<CustomAgreementVo> selectCustomAgreementList() {
        return customInfoMapper.selectCustomAgreementList();
    }

    @Override
    public CustomInfo selectCustomByName(String cusname) {
        return customInfoMapper.selectCustomByName(cusname);
    }

    /**
     * 是否已分配分组
     * @param groupId
     * @return
     */
    @Override
    public int checkCustomExistGroup(Long groupId){
        return customInfoMapper.checkCustomExistGroup(groupId);
    }

    /**
     * 查询是否存在相同的客户名称
     * @param customInfo
     * @return
     */
    @Override
    public String checkCustomNameUnique(CustomInfo customInfo) {
        String customId = customInfo.getId();
        CustomInfo info = customInfoMapper.checkCustomNameUnique(customInfo.getCusname());
        if (StringUtils.isNotNull(info) && !info.getId().equals(customId))
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int selectMyCustomCount(CustomInfo customInfo) {
        return customInfoMapper.selectMyCustomCount(customInfo);
    }

    @Override
    @DataScope(deptAlias = "o", userAlias = "o")
    public List<CustomInfo> selectOperatorShop(CustomInfo customInfo) {
        return customInfoMapper.selectOperatorShop(customInfo);
    }

    @Override
    public List<CustomInfo> selectLeaderShop(CustomInfo customInfo) {
        return customInfoMapper.selectLeaderShop(customInfo);
    }

    @Override
    public List<CustomInfo> selectShopAccordOperator(CustomInfo customInfo) {
        return customInfoMapper.selectShopAccordOperator(customInfo);
    }

    @Override
    public List<CustomInfo> selectOperationSummaryInitData(Date operStartDate, Date operEndDate) {
        return customInfoMapper.selectOperationSummaryInitData(operStartDate, operEndDate);
    }

    /**
     * 新增【客户信息】
     *
     * @param customInfo
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int insertCustomInfo(CustomInfo customInfo)
    {
        String id = SnowflakeIdWorker.generateId().toString();
        customInfo.setId(id);
        customInfo.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        customInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        customInfo.setAllocationStatus("1");
        customInfo.setAllocationUserId(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        customInfo.setAllocationTime(new Date());

        if(customInfo.getContacts() != null && customInfo.getContacts().size() > 0){
            for(int i = 0; i < customInfo.getContacts().size(); i++){
                CustomContact contact = customInfo.getContacts().get(i);
                contact.setId(SnowflakeIdWorker.generateId().toString());
                contact.setCustomId(id);
                contactMapper.insertCustomContact(contact);
            }
        }

        return customInfoMapper.insertCustomInfo(customInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int insertCustomByOperator(CustomInfo customInfo) {
        // 客户基本信息
        String id = SnowflakeIdWorker.generateId().toString();
        customInfo.setId(id);
        if(StringUtils.isNotEmpty(customInfo.getAllocationUserId())){
            customInfo.setAllocationStatus("1");
            customInfo.setAllocationStartTime(DateUtils.getNowDate());
        }else{
            customInfo.setAllocationStatus("0");
        }
        customInfo.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        customInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
        customInfoMapper.insertCustomInfo(customInfo);

        // 联系人信息
        if(customInfo.getContacts() != null && customInfo.getContacts().size() > 0) {
            for(CustomContact contact : customInfo.getContacts()) {
                if(StringUtils.isEmpty(contact.getName()) && StringUtils.isEmpty(contact.getTel())) continue;

                contact.setId(SnowflakeIdWorker.generateId().toString());
                contact.setCustomId(id);
                contactMapper.insertCustomContact(contact);
            }
        }

        if("2".equals(customInfo.getStatus())) {
            // 客户关联运营人员
            CustomOperator operator = new CustomOperator();
            operator.setCustomId(id);
            operator.setUserId(SecurityUtils.getLoginUser().getUser().getUserId().toString());
            operatorMapper.insertCustomOperator(operator);
        }

        return 1;
    }

    /**
     * 修改【客户信息】
     * 
     * @param customInfo
     * @return 结果
     */
    @Override
    public int updateCustomInfo(CustomInfo customInfo)
    {
        customInfo.setUpdateTime(DateUtils.getNowDate());
        return customInfoMapper.updateCustomInfo(customInfo);
    }

    @Override
    public int updateCustomOperStatus(CustomInfo customInfo) {
        return customInfoMapper.updateCustomOperStatus(customInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int abanonCustomInfo(String[] ids, String reason) {
        int count = 0;
        for(int i = 0; i < ids.length; i++) {
            String id = ids[i];
            CustomInfo customInfo = customInfoMapper.selectCustomInfoById(id);
            if(customInfo != null) {
                customInfo.setId(id);
                customInfo.setAllocationStatus("0");
                customInfo.setAllocationUserId(null);
                customInfo.setAllocationTime(null);
                customInfo.setReason(reason);
                customInfo.setStatus("0");
                customInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                count += customInfoMapper.updateCustomInfo(customInfo);
            }
        }
        return count;
    }

    @Override
    public int claimCustomInfo(String[] ids) {
        int count = 0;
        for(int i = 0; i < ids.length;i++) {
            String id = ids[i];
            CustomInfo customInfo = customInfoMapper.selectCustomInfoById(id);
            if(customInfo != null) {
                customInfo.setId(id);
                customInfo.setAllocationStatus("1");
                customInfo.setAllocationUserId(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                customInfo.setAllocationTime(new Date());
                customInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                count += customInfoMapper.updateCustomInfo(customInfo);
            }
        }
        return count;
    }

    @Override
    public int handoverCustomInfo(HandoverParamVo handoverParamVo) {
        int count = 0;
        for(int i = 0; i < handoverParamVo.getCustomIds().length; i++) {
            CustomInfo customInfo = customInfoMapper.selectCustomInfoById(handoverParamVo.getCustomIds()[i]);
            if(customInfo != null) {
                customInfo.setAllocationUserId(handoverParamVo.getUserId());
                customInfo.setAllocationTime(new Date());
                customInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                count += customInfoMapper.updateCustomInfo(customInfo);
            }
        }
        return count;
    }

    @Override
    public int intentCustom(String id) throws Exception {
        CustomInfo customInfo = customInfoMapper.selectCustomInfoById(id);
        if(customInfo != null) {
            if(StringUtils.isEmpty(customInfo.getCusname())){
                throw new Exception("请先维护店铺名称");
            }
            customInfo.setStatus("1");
            customInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
            return customInfoMapper.updateCustomInfo(customInfo);
        }

        return 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int intentCustoms(String[] ids) throws Exception {
        for(String id: ids){
            CustomInfo customInfo = customInfoMapper.selectCustomInfoById(id);
            if(customInfo != null) {
                if(StringUtils.isEmpty(customInfo.getCusname())){
                    throw new Exception("请先完善所有店铺名称");
                }
                customInfo.setStatus("1");
                customInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                customInfoMapper.updateCustomInfo(customInfo);
            }
        }
        return 1;
    }

    @Override
    public int signCustom(String id) throws Exception {
        CustomInfo customInfo = customInfoMapper.selectCustomInfoById(id);
        if(customInfo != null) {
            if(StringUtils.isEmpty(customInfo.getCusname())){
                throw new Exception("请先维护店铺名称");
            }
            customInfo.setStatus("2");
            customInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
            return customInfoMapper.updateCustomInfo(customInfo);
        }
        return 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int signCustoms(String[] ids) throws Exception {
        for(String id: ids){
            CustomInfo customInfo = customInfoMapper.selectCustomInfoById(id);
            if(customInfo != null) {
                if(StringUtils.isEmpty(customInfo.getCusname())){
                    throw new Exception("请先完善所有店铺名称");
                }
                customInfo.setStatus("2");
                customInfo.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId().toString());
                customInfoMapper.updateCustomInfo(customInfo);
            }
        }
        return 1;
    }

    /**
     * 批量删除【客户信息】
     * 
     * @param ids
     * @return 结果
     */
    @Override
    public int deleteCustomInfoByIds(String[] ids)
    {
        return customInfoMapper.deleteCustomInfoByIds(ids);
    }

    /**
     * 删除【客户信息】信息
     * 
     * @param id
     * @return 结果
     */
    @Override
    public int deleteCustomInfoById(String id)
    {
        return customInfoMapper.deleteCustomInfoById(id);
    }

    @Override
    public AjaxResult assignOperators(List<CustomOperator> operators) {
        if(operators != null && operators.size() > 0){
            for(CustomOperator operator : operators){
                CustomOperator shopOperator = operatorMapper.selectCustomOperator(operator.getCustomId(), operator.getUserId());
                if(shopOperator == null) {
                    operatorMapper.insertCustomOperator(operator);
                }
            }
        }
        return AjaxResult.success("分配运营人员成功！");
    }

    @Override
    public AjaxResult transferOperators(List<CustomOperator> operators) throws Exception {
        if(operators != null && operators.size() > 0){
            List<String> customIds = operators.stream().map(CustomOperator::getCustomId).distinct().collect(Collectors.toList());
            for (String customId : customIds){
                CustomInfo customInfo = customInfoMapper.selectCustomInfoById(customId);
                if(StringUtils.isEmpty(customInfo.getCusname())){
                    throw new Exception("请先完善所有店铺名称");
                }
                operatorMapper.deleteCustomOperatorByUserId(customId, SecurityUtils.getLoginUser().getUser().getUserId().toString());
            }

            for(CustomOperator operator : operators){
                CustomOperator shopOperator = operatorMapper.selectCustomOperator(operator.getCustomId(), operator.getUserId());
                if(shopOperator == null) {
                    operatorMapper.insertCustomOperator(operator);
                }
            }
        }
        return AjaxResult.success("分配运营人员成功！");
    }
}
